package xcmg.device.service.agent;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.agent.ServiceStaffQuotaDO;
import xcmg.device.dao.mapper.agent.ServiceStaffQuotaMapper;
import xcmg.device.infra.CalcUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.vo.agent.ServiceStaffQuotaQueryVO;
import xcmg.device.service.vo.agent.ServiceStaffQuotaUseVO;
import xcmg.device.service.vo.agent.ServiceStaffQuotaVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ServiceStaffQuota 后台接口实现类
 *
 * @author huhuawei
 */
@Service
public class ServiceStaffQuotaService {


    private static final Logger logger = LoggerFactory.getLogger(ServiceStaffQuotaService.class);


    @Autowired
    private ServiceStaffQuotaMapper serviceStaffQuotaMapper;

    @Autowired
    private FastGenClient fastGenClient;

    /**
     * 定义启用和禁用
     * 的相应功能
     */
    private static final Integer STATUS_ENABLE = 1;
    private static final Integer STATUS_DISABLE = 0;

    /**
     * 查询列表
     *
     * @param condition
     */
    public PageCommonVO<ServiceStaffQuotaVO> list(SearchCommonVO<ServiceStaffQuotaQueryVO> condition) {
        if (null == condition.getFilters()) {
            condition.setFilters(new ServiceStaffQuotaQueryVO());
        }
        PageCommonVO<ServiceStaffQuotaVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("tt1.STAFF_ID,tt2.create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ServiceStaffQuotaDO> staffQuotaDOList = serviceStaffQuotaMapper.queryList(condition.getFilters());
        List<ServiceStaffQuotaVO> voList = new ArrayList<>();
        for (ServiceStaffQuotaDO entity : staffQuotaDOList) {
            ServiceStaffQuotaVO serviceStaffQuotaVO = new ServiceStaffQuotaVO();
            BeanUtils.copyProperties(entity, serviceStaffQuotaVO);
            voList.add(serviceStaffQuotaVO);
        }

        pageCommonVO.setPageInfo(new PageInfo(staffQuotaDOList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 查询列表
     *
     * @param vo
     */
    public List<ServiceStaffQuotaVO> queryList(ServiceStaffQuotaQueryVO vo) {
        List<ServiceStaffQuotaDO> staffQuotaDOList = serviceStaffQuotaMapper.queryList(vo);
        List<ServiceStaffQuotaVO> voList = new ArrayList<ServiceStaffQuotaVO>();
        for (ServiceStaffQuotaDO entity : staffQuotaDOList) {
            ServiceStaffQuotaVO serviceStaffQuotaVO = new ServiceStaffQuotaVO();
            BeanUtils.copyProperties(entity, serviceStaffQuotaVO);
            voList.add(serviceStaffQuotaVO);
        }
        return voList;
    }


    /**
     * 查询单条记录
     *
     * @param
     */
    public ServiceStaffQuotaVO queryItem(ServiceStaffQuotaQueryVO queryVO) {
        List<ServiceStaffQuotaVO> list = queryList(queryVO);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }


    /**
     * 查询单条记录
     *
     * @param
     */
    public ServiceStaffQuotaVO itemByUserId(String staffId) {
        ServiceStaffQuotaVO ServiceStaffQuotaVO = new ServiceStaffQuotaVO();
        ServiceStaffQuotaDO serviceStaffQuotaDO = serviceStaffQuotaMapper.itemByUserId(staffId);
        if(serviceStaffQuotaDO==null){
            return ServiceStaffQuotaVO;
        }
        BeanUtils.copyProperties(serviceStaffQuotaDO, ServiceStaffQuotaVO);
        return ServiceStaffQuotaVO;
    }


    /**
     * 保存数据
     *
     * @param serviceStaffQuotaVO
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode save(ServiceStaffQuotaVO serviceStaffQuotaVO) throws Exception {
        ErrorCode errorCode = doSave(serviceStaffQuotaVO);
        return ErrorCode.Success;
    }

    /**
     * 使用额度
     *
     * @param serviceStaffQuotaUseVO
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode useQuota(ServiceStaffQuotaUseVO serviceStaffQuotaUseVO) throws Exception {
        Integer countIsDisable = serviceStaffQuotaMapper.countIsDisableByStaffId(serviceStaffQuotaUseVO.getStaffId());
        if (countIsDisable <= 0) {
            return ErrorCode.Success;
        }
        ServiceStaffQuotaVO serviceStaffQuotaVO = new ServiceStaffQuotaVO();
        ServiceStaffQuotaDO staffQuotaDb = serviceStaffQuotaMapper.itemByUserId(serviceStaffQuotaUseVO.getStaffId());
        if (staffQuotaDb != null) {
            staffQuotaDb.setBorrowedAmount(CalcUtil.add(staffQuotaDb.getBorrowedAmount(), serviceStaffQuotaUseVO.getBorrowedAmount()));
            staffQuotaDb.setPendingPayment(CalcUtil.add(staffQuotaDb.getPendingPayment(), serviceStaffQuotaUseVO.getPendingPayment()));
            BeanUtils.copyProperties(staffQuotaDb, serviceStaffQuotaVO);
        } else {
            serviceStaffQuotaVO.setStaffId(serviceStaffQuotaUseVO.getStaffId());
            serviceStaffQuotaVO.setBorrowedAmount(serviceStaffQuotaUseVO.getBorrowedAmount());
            serviceStaffQuotaVO.setPendingPayment(serviceStaffQuotaUseVO.getPendingPayment());
        }
        return doSave(serviceStaffQuotaVO);
    }


    /**
     * 使用额度
     *
     * @param serviceStaffQuotaUseVO
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode useQuotaSubtract(ServiceStaffQuotaUseVO serviceStaffQuotaUseVO) throws Exception {
        ServiceStaffQuotaVO serviceStaffQuotaVO = new ServiceStaffQuotaVO();
        ServiceStaffQuotaDO staffQuotaDb = serviceStaffQuotaMapper.itemByUserId(serviceStaffQuotaUseVO.getStaffId());
        if (staffQuotaDb == null) {
           return ErrorCode.ServicePersonnelDoNotExist;
        }
        staffQuotaDb.setBorrowedAmount(CalcUtil.add(staffQuotaDb.getBorrowedAmount(), serviceStaffQuotaUseVO.getBorrowedAmount()));
        staffQuotaDb.setPendingPayment(CalcUtil.add(staffQuotaDb.getPendingPayment(), serviceStaffQuotaUseVO.getPendingPayment()));
        BeanUtils.copyProperties(staffQuotaDb, serviceStaffQuotaVO);
        return doSave(serviceStaffQuotaVO);
    }

    /**
     * 根据状态，等信息保存数据
     *
     * @param serviceStaffQuotaVO
     */
    private ErrorCode doSave(ServiceStaffQuotaVO serviceStaffQuotaVO) throws Exception {
        preSaveCheck(serviceStaffQuotaVO);
        ServiceStaffQuotaDO serviceStaffQuotaDO = new ServiceStaffQuotaDO();
        BeanUtils.copyProperties(serviceStaffQuotaVO, serviceStaffQuotaDO);
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }
        if (StringUtils.isBlank(serviceStaffQuotaDO.getId())) {
//            serviceStaffQuotaDO.setCreateId(userId);
//            serviceStaffQuotaDO.setCreateName(userName);
            serviceStaffQuotaDO.setCreateDate(new Date());
            serviceStaffQuotaDO.setId(textResult.getValue());
            logger.info("新增操作，serviceStaffQuotaDO:{}", serviceStaffQuotaDO);
        } else {
            serviceStaffQuotaDO.setUpdateDate(new Date());
//            serviceStaffQuotaDO.setUpdateId(userId);
            logger.info("编辑操作，serviceStaffQuotaDO:{}", serviceStaffQuotaDO);
        }
//        serviceStaffQuotaDO.setStatus(1);
        boolean isSuccess = this.merge(serviceStaffQuotaDO) > 0;
        if (!isSuccess) {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }


    /**
     * 保存前信息校验
     */
    private void preSaveCheck(ServiceStaffQuotaVO serviceStaffQuotaVO) throws Exception {
        if (null == serviceStaffQuotaVO) {
            throw new Exception(ErrorCode.IllegalArument.getDesc());
        }
        //TODO如果是提交操作或者某些状态下需要做校验吗？
        //        if (isSubmit&&status？？？) {
        //        }
        if (StringUtils.isNotBlank(serviceStaffQuotaVO.getId())) {
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public int merge(ServiceStaffQuotaDO dto) {
        return serviceStaffQuotaMapper.merge(dto);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode batchDelete(List<String> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return ErrorCode.Failure;
        }
        for (String id : ids) {
            int i = serviceStaffQuotaMapper.deleteByPrimaryKeySelective(id);
            if (i == 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 批量禁用
     *
     * @param ids status:启用是1  禁用是0
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode batchDisable(List<String> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return ErrorCode.Failure;
        }
        ServiceStaffQuotaDO serviceStaffQuotaDO = new ServiceStaffQuotaDO();
        serviceStaffQuotaDO.setStatus(STATUS_DISABLE);
        for (String id : ids) {
            serviceStaffQuotaDO.setId(id);
            int i = serviceStaffQuotaMapper.updateByPrimaryKeySelective(serviceStaffQuotaDO);
            if (i == 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode batchEnable(List<String> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return ErrorCode.Failure;
        }
        ServiceStaffQuotaDO serviceStaffQuotaDO = new ServiceStaffQuotaDO();
        serviceStaffQuotaDO.setStatus(STATUS_ENABLE);
        for (String id : ids) {
            serviceStaffQuotaDO.setId(id);
            int i = serviceStaffQuotaMapper.updateByPrimaryKeySelective(serviceStaffQuotaDO);
            if (i == 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }

    public Integer countIsDisable(String staffId){
        return  serviceStaffQuotaMapper.countIsDisableByStaffId(staffId);
    }
}
